
package util;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
* Contenu de la console de redirection.
*/
public class ConsolePanel extends javax.swing.JPanel implements javax.swing.event.DocumentListener {
    private JTextPane         myTextPane;
	private ConsoleWriter     myWriter;
	private Console           console;

/**
* Construction du composant graphique JPanel contenant la console.
* @param console        composant qui contien le JPanel
*/
	public ConsolePanel(Console console) {
		super();
		this.console = console;
		myTextPane = new JTextPane();
		Document doc = myTextPane.getDocument();
		myWriter = new ConsoleWriter(doc);
		JScrollPane jsp = new JScrollPane(myTextPane);
		setLayout(new BorderLayout());
		add("Center", jsp);
		myTextPane.getDocument().addDocumentListener(this);
    }
    public ConsoleWriter getWriter() {
		return myWriter;
    }
    public void clear() {
		Document doc = myTextPane.getDocument();
		try {
			doc.remove(0, doc.getLength());
		} catch (BadLocationException e) {
			System.err.println(e.getMessage());
		}
    }

	//pour DocumentListener
	public void changedUpdate(DocumentEvent de) {
	}
	public void removeUpdate(DocumentEvent de) {
	}
	public void insertUpdate(final DocumentEvent de) {
		console.setVisible();
		final Document doc = de.getDocument();
		final int i1, i2;
		final int l;
		i1 = de.getOffset();
		i2 = de.getLength();
		l = doc.getLength();
		if (l == i1 + i2) {
			Element e1 = doc.getDefaultRootElement();
			Element e2 = e1.getElement(e1.getElementIndex(i1));
			while (!e2.isLeaf())
			e2 = e2.getElement(e2.getElementIndex(i1));
			final Element e3 = e2;
			AttributeSet as = e3.getAttributes();
			if (as.isDefined(myWriter))
			if (myTextPane.getCaretPosition() != l) {
				myTextPane.setCaretPosition(l);
			}
		}
	}
}
